package org.xue.snowmall.authserver.web;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import entity.UserRecordEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.xue.snowmall.authserver.service.UserRecordService;
import org.xue.snowmall.authserver.utils.HttpUtils;
import org.xue.snowmall.authserver.vo.SocialUser;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    private HttpSession session;

    @Autowired
    private UserRecordService userRecordService;

    @GetMapping(value = "/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code) throws Exception {

        //接到code码 换取token
        Map<String, String> message = new HashMap<>();
        message.put("client_id", "531276879");
        message.put("client_secret", "dcaddfd5c5b3f1e8cd7ebc9c0a55b9b5");
        message.put("grant_type", "authorization_code");
        message.put("redirect_uri", "http://auth.snow-mall.com/oauth2.0/weibo/success");
        message.put("code", code);

        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), message, new HashMap<>());
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到了access_token,转为通用社交登录对象
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //根据token 查询是否有当前用户登录过
            UserRecordEntity isLogin = userRecordService.findByToken(socialUser.getAccess_token());
            if (isLogin != null) {
                //说明此用户已经登录过了
                isLogin.setUsmSocialUid(socialUser.getUid());
                isLogin.setUsmAccessToken(socialUser.getAccess_token());
                isLogin.setUsmExpiresIn(String.valueOf(socialUser.getExpires_in()));
                userRecordService.updateById(isLogin);

                session.setAttribute("user", isLogin);
                return "redirect:http://snow-mall.com";
            } else {
                //当前登录人没有登录过
                //再次调用获取微博授权人信息
                Map<String, String> map = new HashMap<>();
                map.put("access_token", socialUser.getAccess_token());
                map.put("uid", socialUser.getUid());

                HttpResponse get = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), map);
                String s = EntityUtils.toString(get.getEntity());
                JSONObject jsonObject = JSON.parseObject(s);
                String name = (String) jsonObject.get("name");
                String screen_name = (String) jsonObject.get("screen_name");
                String city = (String) jsonObject.get("city");
                String profile_image_url = (String) jsonObject.get("profile_image_url");
                String gender = (String) jsonObject.get("gender");

                UserRecordEntity userRecordEntity = new UserRecordEntity();
                userRecordEntity.setUsmName(name);
                userRecordEntity.setUsmNickname(screen_name);
                userRecordEntity.setUsmCity(city);
                userRecordEntity.setUsmHeader(profile_image_url);
                userRecordEntity.setUsmGender("m".equals(gender) ? "0" : "1");
                userRecordEntity.setUsmCreateTime(new Date());
                userRecordEntity.setUsmExpiresIn(String.valueOf(socialUser.getExpires_in()));
                userRecordEntity.setUsmId(new Long(socialUser.getUid()));
                userRecordEntity.setUsmAccessToken(socialUser.getAccess_token());
                userRecordService.save(userRecordEntity);

                session.setAttribute("user", userRecordEntity);
                return "redirect:http://snow-mall.com";
            }
        } else {
            return "redirect:http://auth.snow-mall.com/login.html";
        }
    }

}
